package com.cet.spring_batch_study.jobs.custom;

import org.springframework.batch.item.*;

import java.util.List;

public class CustomItemReader<T> implements ItemReader<T>, ItemStream {

    private final List<T> items;
    private long currentIndex = 0L;
    private static final String CURRENT_INDEX = "current.index";

    public CustomItemReader(List<T> items) {
        this.items = items;
    }

    @Override
    public T read() throws
            ParseException {

        if (currentIndex < items.size()) {
            return items.get((int) currentIndex++);
        }

        return null;
    }

    @Override
    public void open(ExecutionContext executionContext) throws ItemStreamException {
        if (executionContext.containsKey(CURRENT_INDEX)) {
            currentIndex = executionContext.getLong(CURRENT_INDEX);
        }
        else {
            currentIndex = 0;
        }
    }

    @Override
    public void update(ExecutionContext executionContext) throws ItemStreamException {
        executionContext.putLong(CURRENT_INDEX, currentIndex);
    }

    @Override
    public void close() throws ItemStreamException {}
}